package com.library.rest.okhttp;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

import static com.library.rest.ApiServiceManager.deviceNo;
import static com.library.rest.ApiServiceManager.token;
import static com.library.rest.ApiServiceManager.tokenId;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-08 18:08
 * @version: 9.1.0
 */
public class OkHttpHeaderInterceptro implements Interceptor {
    private static DateFormat dateTimeFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    Random mRandom = new Random();
    private static final String KEY_A = "TKIHDEKD6FOKKKMTFd68";
    private static final String KEY_B = "QCTD458JDYKTKIHDECTD";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder rBuild = chain.request().newBuilder();
        Date nowDate = new Date();
        String time = dateTimeFormat.format(nowDate);
        //            String sn = String.valueOf(mRandom.nextInt(100000));
        String body = stringifyRequestBody(chain.request());
        StringBuffer buffer = new StringBuffer();
        buffer.append(body);
        String deviceId = deviceNo;
        //            if (BuildConfig.DEBUG) {
        //                deviceId = "111";
        //            }
        rBuild.addHeader("time", time)
            //                .addHeader("sn", sn)
            //小写 MD5:固定部 A+time+sn+data 部+ 固定部 B
            //                .addHeader("sign", MD5.string2MD5(buffer.toString()))
            //                .addHeader("ver", "android1.0")
            //                .header("Content-Type", "*/*")
            .header("deviceId", deviceId)
            .header("Encoding", "UTF-8")
            .header("tokenId", tokenId == null ? "" : tokenId)
            .header("token", token == null ? "" : token);

        return chain.proceed(rBuild.build());
    }

    private static String stringifyRequestBody(Request request) {
        try {
            final Request copy = request.newBuilder().build();
            if (copy != null) {
                final Buffer buffer = new Buffer();
                RequestBody requestBody = copy.body();
                if (requestBody != null) {
                    requestBody.writeTo(buffer);
                    return buffer.readUtf8();
                }
            }

        } catch (final IOException e) {
            return "did not work";
        }
        return "";
    }
}
